<template>
  <div v-loading="loading" element-loading-text="加载中..." class="page-bg">
    <el-card class="box-card">
      <div slot="header" class="clearfix card-header">
        <span class="main-title">设备类型统计故障次数</span>
        <div class="header-spacer"></div>
        <el-button
          class="download-btn"
          type="primary"
          size="small"
          @click="downloadChart"
        >
          下载图表
        </el-button>
      </div>
      <!-- 添加时间范围选择器 -->
      <div class="query-container">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              :clearable="true"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="chart-table-row">
        <div id="main" class="chart-area"></div>
        <div class="stat-table-side" v-if="statTableData.length && (!dateRange || dateRange.length === 0)">
          <div class="stat-table-title">统计指标</div>
          <el-table :data="statTableData" border size="mini" header-cell-class-name="stat-table-header">
            <el-table-column prop="name" label="统计指标" width="120"></el-table-column>
            <el-table-column prop="value" label="统计值" width="120"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { getToken } from "@/utils/auth";

export default {
  name: "FaultChart",
  data() {
    return {
      dateRange: [], // 时间范围
      chart: null, // 保存图表实例
      loading: false,
      statTableData: [],
    };
  },
  mounted() {
    this.fetchData();
    this.fetchStatTableData();
  },
  beforeDestroy() {
    // 组件销毁前销毁图表实例
    if (this.chart) {
      this.chart.dispose();
      this.chart = null;
    }
  },
  methods: {
    // 查询按钮点击事件
    handleQuery() {
      this.fetchData();
    },
    // 重置按钮点击事件
    handleReset() {
      this.dateRange = [];
      this.fetchData();
    },
    async fetchData() {
      try {
        this.loading = true;
        const token = getToken();
        const params = {};

        if (this.dateRange && this.dateRange.length === 2) {
          params.startDate = this.dateRange[0];
          params.endDate = this.dateRange[1];
        }

        console.log("Sending request with params:", params);

        const response = await axios.get(
          `${process.env.VUE_APP_BASE_API}/wareHouses/NumberOfPower`,
          {
            params,
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );

        console.log("Received response:", response);

        const jsonData = response.data;

        if (jsonData && Array.isArray(jsonData.source) && jsonData.source.length > 0) {
          // 有数据，正常渲染
          const chartData = jsonData.source.map((item) => ({
            equipmentTypeName: item["设备类型"],
            failureCount: item["故障次数"],
          }));
          this.initChart(chartData);
        } else {
          // 无数据，弹窗并回到默认查询
          this.$message.warning("查询范围无数据，返回默认查询");
          if (this.dateRange && this.dateRange.length > 0) {
            this.dateRange = [];
            this.$nextTick(() => {
              this.fetchData();
            });
          }
        }
      } catch (error) {
        console.error("获取数据失败:", error);
        console.error("Error details:", {
          message: error.message,
          response: error.response,
          request: error.request,
        });
        this.$message.error(
          error.response?.data?.message || "获取数据失败，请检查网络连接"
        );
      } finally {
        this.loading = false;
      }
    },
    initChart(data) {
      const chartDom = document.getElementById("main");
      // 如果已经有图表实例，先销毁
      if (this.chart) {
        this.chart.dispose();
      }
      this.chart = echarts.init(chartDom);

      const option = {
        title: {
          text:
            this.dateRange.length === 2
              ? `设备故障统计（${this.dateRange[0]} 至 ${this.dateRange[1]}）`
              : "",
          left: "center",
          top: 10,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        grid: {
          top: "80px",
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.map((item) => item.equipmentTypeName),
          axisLabel: {
            rotate: 45,
            align: "right",
          },
        },
        yAxis: {
          type: "value",
          name: "故障次数",
          minInterval: 1, // 确保Y轴显示整数
        },
        series: [
          {
            type: "bar",
            data: data.map((item) => ({
              value: item.failureCount,
              itemStyle: {
                color: "#5470c6",
              },
            })),
            label: {
              show: true,
              position: "top",
              formatter: "{c}",
            },
          },
        ],
      };

      this.chart.setOption(option);

      // 添加窗口大小改变时的自适应
      window.addEventListener("resize", () => {
        this.chart && this.chart.resize();
      });

      // 绑定点击事件，只在点击柱子时跳转
      this.chart.off('click'); // 先解绑，防止重复绑定
      this.chart.on('click', (params) => {
        if (
          params.componentType === 'series' &&
          params.seriesType === 'bar' &&
          params.name // 有柱子名称
        ) {
          const number = params.name;
          this.$router.push({ name: 'NumberOfDevice', params: { number } });
        }
      });
    },
    downloadChart() {
      if (!this.chart) {
        this.$message.warning("暂无图表数据");
        return;
      }

      try {
        // 获取当前时间作为文件名
        const now = new Date();
        const dateStr =
          this.dateRange && this.dateRange.length === 2
            ? `${this.dateRange[0]}_${this.dateRange[1]}`
            : `${now.getFullYear()}${(now.getMonth() + 1)
                .toString()
                .padStart(2, "0")}${now.getDate().toString().padStart(2, "0")}`;

        const fileName = `设备类型故障统计_${dateStr}.png`;

        // 获取图表图片的base64数据
        const imgData = this.chart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.href = imgData;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("图表下载成功");
      } catch (error) {
        console.error("下载图表失败:", error);
        this.$message.error("下载图表失败，请重试");
      }
    },
    async fetchStatTableData() {
      try {
        const token = getToken();
        const response = await axios.get(
          `${process.env.VUE_APP_BASE_API}/wareHouses/RepairNumber`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        if (response.data) {
          const data = response.data;
          this.statTableData = [
            { name: "25%分位数", value: data["25th"] || 'N/A' },
            { name: "50%分位数", value: data["50th"] || 'N/A' },
            { name: "75%分位数", value: data["75th"] || 'N/A' },
            { name: "标准差", value: data.standardDeviation || 'N/A' },
            { name: "平均值", value: data.average || 'N/A' },
            { name: "数量", value: data.count || 'N/A' },
            { name: "最大值", value: data.max || 'N/A' },
            { name: "最小值", value: data.min || 'N/A' }
          ];
        }
      } catch (error) {
        this.$message.error("获取统计表数据失败");
      }
    },
  },
};
</script>

<style scoped>
.page-bg {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 32px 0;
}

.box-card {
  margin: 0 auto;
  max-width: 1600px;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding-bottom: 24px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding-bottom: 8px;
}

.main-title {
  font-size: 22px;
  font-weight: bold;
  color: #222;
  letter-spacing: 1px;
}

.download-btn {
  margin-left: 12px;
}

.query-container {
  margin-bottom: 32px;
  padding: 8px 0 0 0;
}

.chart-table-row {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  width: 100%;
  margin-top: 12px;
}

.chart-area {
  flex: 1;
  min-width: 0;
  height: 700px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 12px;
}

.stat-table-side {
  margin-left: 40px;
  min-width: 280px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  border-radius: 8px;
  padding: 16px 12px 12px 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-table-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  letter-spacing: 1px;
}

.stat-table-header {
  background: #f0f2f5 !important;
  color: #333 !important;
  font-weight: bold;
}

.header-spacer {
  flex: 1;
}

@media (max-width: 1200px) {
  .chart-table-row {
    flex-direction: column;
  }
  .stat-table-side {
    margin-left: 0;
    margin-top: 24px;
    width: 100%;
    min-width: 0;
  }
}
</style>
